package com.itheima.httpClient;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 *    1、创建HttpClient对象
 *    2、创建请求方式对象，HttpGet HttpPost
 *    3、封装请求信息：请求头和请求体
 *    4、发送请求获取响应对象 response
 *    5、根据response对象获取响应头和响应体
 *    6、释放资源
 */


public class HttpClientGet {
    public static void main(String[] args) throws Exception {
        String urlIndex="http://www.itcast.cn";

        //发送请求，获取数据
        //2.1
        CloseableHttpClient httpClient = HttpClients.createDefault();//浏览器

        //创建请求对象,请求对象
        HttpGet httpGet = new HttpGet(urlIndex);

        //设置请求头
        httpGet.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36");

        //发送请求，获取响应
        CloseableHttpResponse resp = httpClient.execute(httpGet);

        //状态码
        int statusCode = resp.getStatusLine().getStatusCode();
        System.out.println("状态码："+statusCode);


        if(statusCode==200){
            Header[] headers = resp.getHeaders("Content-Type");
            for (Header h:headers) {
                System.out.println(h.getValue());
            }

            //获取响应体
            HttpEntity entity = resp.getEntity();

            String s = EntityUtils.toString(entity);
            System.out.println(s);


        }

        resp.close();
        httpClient.close();


    }
}
